package com.youmingxing.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.TextView;

import com.youmingxing.AllStarApp;
import com.youmingxing.R;
import com.youmingxing.activity.selfInfo.MyAuditionGoingActivity;
import com.youmingxing.adpter.MyNewsAdapter;
import com.youmingxing.data.MyNews;
import com.youmingxing.data.MyNewsDao;
import com.youmingxing.network.BaseJsonHandler;
import com.youmingxing.network.SelfInfoApi;
import com.youmingxing.view.DialogManager;
import com.youmingxing.view.RefreshListView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;


/**
 * @author chihiro(xuchang)
 * @since 2015-9-26
 */

public class MyNewsActivity extends BaseActivity implements RefreshListView.OnLoadMoreListener {
    RefreshListView myNewsList;
    List<MyNews> list = new ArrayList<>();
    MyNewsAdapter myNewsAdapter;
    MyNewsDao newsDao;
    long timestamp = System.currentTimeMillis();

    public final static String EXTRAS_HAVE_NEW = "have_news";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        BaseSetContentView(R.layout.activity_my_news);
        setTopbarName(R.string.title_activity_my_news);
        myNewsList = (RefreshListView) findViewById(R.id.list_my_news);
        initDB();
        initView();
    }

    private void initDB() {
        newsDao = AllStarApp.getDaoSession(this).getMyNewsDao();
    }

    private void loadHistory() {
        List<MyNews> querySet = newsDao.queryBuilder().orderDesc(MyNewsDao.Properties.Createtime)
                .where(MyNewsDao.Properties.Createtime.lt(timestamp)).limit(20).list();
        if (querySet.size() < 20) {
            //没有更多消息
            myNewsList.noMoreData();
        } else {
            //有更多消息
            timestamp = querySet.get(querySet.size() - 1).getCreatetime();
        }
        for (int i = 0; i < querySet.size(); i++) {
            list.add(querySet.get(i));
        }
        myNewsList.endLoadMore();
        myNewsAdapter.setData(list);
    }

    private void initView() {
        boolean showClearBtn = false;
        myNewsList.setOnLoadMoreListener(this);
        myNewsList.setFootVisible(false);
        ((TextView) findViewById(R.id.no_data_title)).setText(R.string.no_news_hint);
        if (newsDao.count() > 0) showClearBtn = true;
        Bundle bundle = getIntent().getExtras();
        if (bundle.getBoolean(EXTRAS_HAVE_NEW)) { //有新消息
            DialogManager.showDialog(this);
            SelfInfoApi.getMyNews(handler);
            showClearBtn = true;
        } else {
            //没有新消息
        }

        if (showClearBtn) {
            setLeftAndrightTv(true, true, false, R.string.clear_my_news, null, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //清空所有消息
                    newsDao.deleteAll();
                    list.clear();
                    myNewsAdapter.setData(list);
                    findViewById(R.id.hint_layout).setVisibility(View.GONE);
                    setLeftAndrightTv(true, false, false, -1, null, null, null);
                }
            }, null);
        }
        myNewsList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (id < 0) {
                    return;
                }
                MyNews myNews = list.get(position);
                Intent intent;
                if (myNews.getType() == 1 || myNews.getType() == 2 || myNews.getType() == 4) {
                    intent = new Intent(MyNewsActivity.this, ContentDetailActivity.class);
                    intent.putExtra("content_id", myNews.getItem_id());
                    startActivity(intent);
                } else if (myNews.getType() == 3) {
                    intent = new Intent(MyNewsActivity.this, MyAuditionGoingActivity.class);
                    intent.putExtra("id", myNews.getItem_id());
                    startActivity(intent);
                }
            }
        });


        //有历史消息,显示查看更早消息footer
        if (newsDao.count() == 0) {
            findViewById(R.id.btn_load_history).setVisibility(View.GONE);
        }
        myNewsAdapter = new MyNewsAdapter(this);
        myNewsList.setAdapter(myNewsAdapter);
        myNewsAdapter.setData(list);
    }

    //更早消息监听
    public void onLoadHistoryClick(View view) {
        findViewById(R.id.hint_layout).setVisibility(View.GONE);
        myNewsList.setFootVisible(true);
        myNewsList.setAdapter(myNewsAdapter);
        loadHistory();
    }


    BaseJsonHandler handler = new BaseJsonHandler(this) {
        @Override
        public void onSuccessWithData(JSONObject response) {
            if (response.optInt("status") == 200) {
                findViewById(R.id.no_data_layout).setVisibility(View.GONE);
                JSONArray data = response.optJSONArray("data");
                for (int i = 0; i < data.length(); i++) {
                    MyNews myNews = parseToObject(data.optJSONObject(i));
                    list.add(myNews);
                    if (i == data.length() - 1) {
                        //最后一条
                        timestamp = myNews.getCreatetime();
                    }
                }
                myNewsList.setAdapter(myNewsAdapter);
                myNewsAdapter.setData(list);
            }
        }
    };


    public MyNews parseToObject(JSONObject data) {
        MyNews myNews = new MyNews();
        myNews.setU_id(data.optInt("u_id"));
        myNews.setNickname(data.optString("nickname"));
        myNews.setHeadimg(data.optString("headimg"));
        myNews.setType(data.optInt("type"));
        myNews.setAlert(data.optString("alert"));
        myNews.setContent(data.optString("content"));
        myNews.setItem_id(data.optInt("item_id"));
        myNews.setThumbnail(data.optString("thumbnail"));
        myNews.setCreatetime(data.optLong("createtime"));
        newsDao.insert(myNews);
        return myNews;
    }

    @Override
    public void onLoadMore() {
        loadHistory();
    }
}
